package org.jasper.impl.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * Created by OP038074 on 2018/7/19.
 */
public class IoUtils {

    public static final Charset UTF8_CHARSET = Charset.forName("UTF-8");

    public static byte[] readBytesFromInputStream(InputStream input) throws IOException {
        return readBytesFromInputStream( input, true );
    }

    public static byte[] readBytesFromInputStream(InputStream input, boolean closeInput) throws IOException {
        try {
            byte[] buffer = createBytesBuffer( input );
            ByteArrayOutputStream output = new ByteArrayOutputStream( buffer.length );

            int n = 0;
            while ( -1 != ( n = input.read( buffer ) ) ) {
                output.write( buffer, 0, n );
            }
            return output.toByteArray();
        } finally {
            try {
                if ( closeInput ) {
                    input.close();
                }
            } catch (Exception e) {
                // ignore
            }
        }
    }

    private static byte[] createBytesBuffer( InputStream input ) throws IOException {
        return new byte[Math.max(input.available(), 8192)];
    }

    public static String asSystemSpecificPath(String urlPath, int colonIndex) {
        String ic = urlPath.substring( Math.max( 0, colonIndex - 2 ), colonIndex + 1 );
        if  ( ic.matches( "\\/[A-Z]:" ) ) {
            return urlPath.substring( colonIndex - 2 );
        } else if  ( ic.matches( "[A-Z]:" ) ) {
            return urlPath.substring( colonIndex - 1 );
        } else {
            return urlPath.substring( colonIndex + 1 );
        }
    }
}
